/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.dusin.teachassist.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author dusin
 */
public class CounterFile {
     public static void writeFile(String filename, long count) {
         PrintWriter out=null;
        try {
            out= new PrintWriter(new FileWriter(filename));
            out.println(count);           
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(out!=null)
                out.close();
        }
    }

    public static long readFile(String filename) {
        File f = new File(filename);
        long count = 0;
        if (!f.exists()) {
            writeFile(filename, 0);
        }
        BufferedReader in=null;
       try {
            in = new BufferedReader(new FileReader(f));
            try {
                count = Long.parseLong(in.readLine());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
           if(in!=null){
               try {
                   in.close();
               } catch (IOException ex) {
                   ex.printStackTrace();
               }
           }
       }
        return count;
    }
}
